<?php
/**
 * Created by PhpStorm.
 * User: Vito
 * Date: 2022/1/21
 */

namespace app\api\exception;

use app\common\CodeMessage;
use app\common\exception\CommonException;
use think\exception\Handle;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    /**
     * 记录日志
     * @param Throwable $exception
     */
    public function report(Throwable $exception): void
    {
        if ( !$exception instanceof CommonException || !env('app_debug') ) {
            parent::report($exception); // TODO: Change the autogenerated stub
        }
    }

    /**
     * 处理异常
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        $code    = 1;
        $status  = false;
        $message = 'error';

        if ( $e instanceof HttpResponseException ) {
            return parent::render($request, $e);
        }

        if ( env('app_debug') && ($request->param('render') || config('web.throw')) ) {
            return parent::render($request, $e);
        }

        if ( $e instanceof CommonException || env('app_debug') ) {
            $message = $e->getMessage();

            if ( !$message && $e instanceof CommonException ) {
                $message = CodeMessage::getMessage($e->getStatusCode());
            }

            if ( !$e instanceof CommonException ) {
                $message .= ' in ' . $e->getFile() . ' line ' . $e->getLine();
            }
        } else {
            $code = CodeMessage::SERVICE_ERROR;
        }

        if ( method_exists($e, 'getStatusCode') ) {
            $code = $e->getStatusCode();
        }

        $args = [
            'status'  => $status,
            'code'    => $code,
            'message' => $message,
        ];

        return \response_api($args);
    }
}